package com.example.wearing;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.example.wearing.javabean.ProvinceBean;
import com.example.wearing.javabean.User;
import com.example.wearing.tools.ImageUtil;
import com.example.wearing.tools.JsonFileReader;
import com.google.android.material.snackbar.Snackbar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


//注册页面
public class RegisterActivity extends AppCompatActivity implements Runnable {
    EditText u_name, u_pwd, u_pwd2;
    Button registerBtn;
    String userName, userPwd, userPwd2, userCity;
    private static final String TAG = "RegisterActivity";
    private Handler handler;
    String jdbcUrl, jdbcUser, jdbcPassword;

    //处理城市选择
    private TextView mTextViewAddress;
    OptionsPickerView pvOptions;
    //  省份
    ArrayList<List<String>> provinceList = new ArrayList<>();
    ArrayList<ProvinceBean> provinceBeanList = new ArrayList<>();
    //  城市
    ArrayList<String> cities;
    ArrayList<List<String>> cityList = new ArrayList<>();
    //  区/县
    ArrayList<String> district;
    ArrayList<List<String>> districts;
    ArrayList<List<List<String>>> districtList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        //获取layout页面的输入和btn
        u_name = findViewById(R.id.u_name);
        u_pwd = findViewById(R.id.u_pwd);
        u_pwd2 = findViewById(R.id.u_pwd2);
        registerBtn = findViewById(R.id.registerBtn);

        //检查sharedPreference
        SharedPreferences sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);
        //获取数据
        jdbcUrl = sp.getString("jdbc_url", "");
        jdbcUser = sp.getString("jdbc_user","");
        jdbcPassword = sp.getString("jdbc_password","");
        //返回
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        registerBtn.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
            @Override
            public void onClick(View view) {
                signUp();
            }
        });


        //处理城市选择器-------------------------------------------------------------------------------
        //  创建选项选择器
        pvOptions = new OptionsPickerView(this);
        mTextViewAddress = findViewById(R.id.tv_address);

        //  获取json数据
        String province_data_json = JsonFileReader.getJson(this, "province_data.json");
        //  解析json数据
        parseJson(province_data_json);

        //  设置三级联动效果
        pvOptions.setPicker(provinceList, cityList, districtList, true);
//        Log.i(TAG, "onCreate: Province："+provinceBeanList);
//        Log.i(TAG, "onCreate: City："+cityList);

        //  设置选择的三级单位
//        pvOptions.setLabels("省", "市", "区");
        pvOptions.setTitle("选择城市");

        //  设置是否循环滚动
        pvOptions.setCyclic(false, false, false);

        // 设置默认选中的三级项目
        pvOptions.setSelectOptions(0, 0, 0);
        //  监听确定选择按钮
        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                //返回的分别是三个级别的选中位置
                String city = provinceBeanList.get(options1).getPickerViewText();
                Log.i(TAG, "onOptionsSelect: provinceBeanList-city:"+city);
                String address;
                //  如果是直辖市或者特别行政区只设置市和区/县
                if ("北京市".equals(city) || "上海市".equals(city) || "天津市".equals(city) || "重庆市".equals(city) || "澳门".equals(city) || "香港".equals(city)) {
                    address = provinceBeanList.get(options1).getPickerViewText()
                            + "-" + districtList.get(options1).get(option2).get(options3);
                } else {
                    address = provinceBeanList.get(options1).getPickerViewText()
                            + "-" + cityList.get(options1).get(option2)
                            + "-" + districtList.get(options1).get(option2).get(options3);
                }
                mTextViewAddress.setText(address);
            }
        });

        //  点击弹出选项选择器
        mTextViewAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pvOptions.show();
            }
        });

        //------------------------------------------------------------------------------------------


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        if(item.getItemId()==android.R.id.home){
            finish();
            return true;
        }
        super.onOptionsItemSelected(item);
        return true;
    }

    //账号密码注册
    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    private void signUp() {
        userName = u_name.getText().toString().trim();//trim用于去前后空格
        userPwd = u_pwd.getText().toString().trim();
        userPwd2 = u_pwd2.getText().toString().trim();
        userCity = mTextViewAddress.getText().toString().trim();

        //判断是否有空值
        if(userName.isEmpty()||userPwd.isEmpty()||userPwd2.isEmpty()){
            Toast.makeText(getApplicationContext(), "请填写所有输入框", Toast.LENGTH_LONG).show();
            return;
        }else if(!userPwd.equals(userPwd2)){
            //判断两次密码一致
            Toast.makeText(getApplicationContext(), "两次输入密码不一致", Toast.LENGTH_LONG).show();
            return;
        }else if(userCity.equals("点击选择地址")){
            //判断是否选择城市
            Toast.makeText(getApplicationContext(), "请选择所在城市", Toast.LENGTH_LONG).show();
            return;
        }else{
            //判断该用户名是否已被注册过
            handler = new Handler(){
                @Override
                public void handleMessage(@NonNull Message msg){
                    Log.i(TAG, "handleMessage: 收到消息");

                    if(msg.what == 1){
                        //接收消息
                        int res = (int) msg.obj;
                        if(res == 1){
                            //说明注册过
                            Toast.makeText(getApplicationContext(), "注册失败：用户已存在", Toast.LENGTH_LONG).show();

                        }else if(res == 2){
                            //未被注册过，符合条件，存入数据库
                            Toast.makeText(getApplicationContext(), "注册成功", Toast.LENGTH_SHORT).show();
                            //返回登陆界面
                            Intent login = new Intent(RegisterActivity.this, LoginActivity.class);
                            startActivity(login);
                            finish();

                        }
                    }
                    super.handleMessage(msg);
                }
            };

            //判断是否注册过，未注册将新用户数据插入数据库
            Thread thread = new Thread(this);
            thread.start();

        }

    }






    //创建线程类，实现Runnable接口，用于查询用户数据
    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void run() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection cn = DriverManager.getConnection(jdbcUrl,jdbcUser,jdbcPassword);
            String sql = "select * from user where u_name = '"+userName+"'";
            Statement st = (Statement)cn.createStatement();
            ResultSet rs = st.executeQuery(sql);
            System.out.println("查找成功");
            int queryCode;
            rs.last(); // 将光标移动到最后一行
            int rowCount = rs.getRow(); // 得到当前行号，即结果集记录数
            Log.i(TAG, "run: rowcount:"+rowCount);
            rs.beforeFirst();//将光标移回首行
            rs.next();

            if(rowCount > 0){
                //说明注册过
                queryCode = 1;
            }else{
                //未被注册过，符合条件，存入数据库
                //设置默认头像
                Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.userimg);
                String imageToBase64 = ImageUtil.imageToBase64(bitmap);
                String insertSql = "INSERT INTO user (u_name,u_pwd,u_city,u_img) VALUES ('"+userName+"','"+userPwd+"','"+userCity+"','"+imageToBase64+"')";
                int result = st.executeUpdate(insertSql);// 返回值代表收到影响的行数
                Log.i(TAG, "run: 插入数据成功"+result+"行----"+userName);
                queryCode = 2;
            }

            //发送消息
            Message msg = handler.obtainMessage(1, queryCode);
            handler.sendMessage(msg);
            Log.i(TAG, "run: 消息已发送---查询结果");

            rs.close();
            st.close();
            cn.close();
        } catch (ClassNotFoundException e) {
            Log.i(TAG, "run:SQL fail!!!__"+e);
            e.printStackTrace();
        } catch (SQLException e) {
            Log.i(TAG, "run:SQL fail!!!__"+e);
            e.printStackTrace();
        }
    }

    //  解析json填充集合
    public void parseJson(String str) {
        try {
            //  获取json中的数组
            JSONArray jsonArray = new JSONArray(str);
            //  遍历数据组
            for (int i = 0; i < jsonArray.length(); i++) {
                //  获取省份的对象
                JSONObject provinceObject = jsonArray.optJSONObject(i);
                //  获取省份名称放入集合
                String provinceName = provinceObject.getString("name");
                ArrayList<String> province = new ArrayList<>();//   声明存放省份的集合
                province.add(provinceName);
                provinceList.add(province);
                provinceBeanList.add(new ProvinceBean(provinceName));
                //  获取城市数组
                JSONArray cityArray = provinceObject.optJSONArray("city");
                cities = new ArrayList<>();//   声明存放城市的集合
                districts = new ArrayList<>();//声明存放区县集合的集合
                //  遍历城市数组
                for (int j = 0; j < cityArray.length(); j++) {
                    //  获取城市对象
                    JSONObject cityObject = cityArray.optJSONObject(j);
                    //  将城市放入集合
                    String cityName = cityObject.optString("name");
                    cities.add(cityName);
                    district = new ArrayList<>();// 声明存放区县的集合
                    //  获取区县的数组
                    JSONArray areaArray = cityObject.optJSONArray("area");
                    //  遍历区县数组，获取到区县名称并放入集合
                    for (int k = 0; k < areaArray.length(); k++) {
                        String areaName = areaArray.getString(k);
                        district.add(areaName);
                    }
                    //  将区县的集合放入集合
                    districts.add(district);
                }
                //  将存放区县集合的集合放入集合
                districtList.add(districts);
                //  将存放城市的集合放入集合
                cityList.add(cities);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
